package com.suishoupai.xmb.task;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.suishoupai.xmb.dao.CutGoodsMapper;
import com.suishoupai.xmb.dao.CutGoodsSnapshotMapper;
import com.suishoupai.xmb.dao.CutOrdersMapper;
import com.suishoupai.xmb.dao.CutUserBuyMapper;
import com.suishoupai.xmb.entity.GoodsSnapshot;
import com.suishoupai.xmb.entity.OrderStatusEnum;
import com.suishoupai.xmb.entity.Orders;
import com.suishoupai.xmb.exception.XmbException;
import com.suishoupai.xmb.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by caojian on 2017/4/17.
 */
@Component
public class OrdersTask {
    private static final Log LOG = LogFactory.getLog(OrdersTask.class);

    @Autowired
    private CutOrdersMapper cutOrdersMapper;
    @Autowired
    private CutGoodsSnapshotMapper cutGoodsSnapshotMapper;
    @Autowired
    private CutGoodsMapper cutGoodsMapper;
    @Autowired
    private CutUserBuyMapper cutUserBuyMapper;

    @Value("${order.timeout}")
    private long timeout;
    @Value("${order.deal-num}")
    private int dealNum;
    @Value("${order.timeout-score}")
    private int orderTimeoutScore;

    /**
     * 订单超时
     */
    @Scheduled(fixedRate = 60000)
    public void timeout() {
        long startTime = System.currentTimeMillis();
        LOG.info("开始处理超时未支付订单，开始时间：" + startTime);
        PageUtil.startPage(1, dealNum, false);
        List<Orders> ordersList = cutOrdersMapper.selectOvertimeNoPayOrdersList(startTime - timeout);
        try {
            for (Orders orders : ordersList) {
                this.doTimeOut(orders.getId(), orders.getUserId());
            }
        } catch (XmbException e) {
            LOG.info("订单处理异常---" + e.getError());
        }
        long endTime = System.currentTimeMillis();
        LOG.info("结束执行超时未支付订单，花费时间：" + (endTime - startTime));
    }

    /**
     * 执行操作
     */
    @Transactional
    public void doTimeOut(long ordersId, long userId) throws XmbException {
        List<GoodsSnapshot> goodsSnapshotList = cutGoodsSnapshotMapper.selectByOrdersId(ordersId);
        for (GoodsSnapshot goodsSnapshot : goodsSnapshotList) {
            long goodsId = goodsSnapshot.getGoodsId();
            //释放库存
            if (cutGoodsMapper.addNumber(goodsId, goodsSnapshot.getCount()) == 0) {
                throw XmbException.newError("更新goods失败" + goodsId);
            }
        }
        //更新订单状态
        Orders updateOrders = new Orders();
        updateOrders.setId(ordersId);
        updateOrders.setDescription("超时未支付");
        updateOrders.setStatus(OrderStatusEnum.CLOSE.getValue());
        if (cutOrdersMapper.updateByPrimaryKeyWhenStatus(updateOrders, OrderStatusEnum.WAIT_PAY.getValue()) == 0) {
            throw XmbException.newError("更新orders失败" + ordersId);
        }
        //减少用户评分
        if (cutUserBuyMapper.orderCloseByPrimaryKey(userId, orderTimeoutScore) == 0) {
            throw XmbException.newError("更新UserBuy失败" + userId);
        }
    }
}
